<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use app\index\model\Type;
use app\index\model\Course;
use app\index\model\SubUser;
use app\index\model\KnowUserLog;
use app\index\model\SubUserInfo;
use app\index\model\SubQuestion;
use app\index\model\SubTestpaper;
use app\index\service\UserService;



class Sub  extends Common
{
	public function __construct(Request $request){
		parent::__construct();
		$param = $request->param();
		if(!user() && !$param['preview']) {
			if($request->isAjax()){
				die(json_encode(['code'=>400,'msg'=>'请先登录']));
			}else{
				$this->checkLogin();
			}
		}
	}


	public function submit_ques(Request $request){
		$param = $request->param();
		$id = explode('-',$param['id']);
		$tId = $id[0];
		$qId = count($id) < 2 ? $id[0] : $id[1];
		$result = SubQuestion::disposeUserAnswer($tId,$qId,$param['answer'],$param['helper']);
		$testpaper = SubTestpaper::getPaperQues($tId);
		$quesIds = explode(',',$testpaper['ques_id']);
		$status = 'natural';
		$data = Course::getDataOne($param['course']);
		$data['status'] = 0;
		UserService::changeUserLog($data);
		if($quesIds[count($quesIds)-1] == $qId) {
			$userQues = SubUser::getTestQuesIds($tId, $quesIds, 1);
			if ($userQues[$qId] == 1){
				$wrontQues = SubUserInfo::getQuesIds(['quesIds'=>$quesIds]);
				$points = count($quesIds)-count($wrontQues);
				$status = 'last';
				KnowUserLog::updateData([
					'id' => $param['course'],
					'points' => $points,
					'status' => 1,
				]);
			}
		}
		return json([
			'code' => 200,
			'status' => $status,
			'result' => $result,
			'counts' => count($quesIds),
			'points' => $points ?: 0,
		]);
	}
}